package cn.itsource.pethome.system.login.contrlller;


import cn.itsource.pethome.config.WxConfig;
import cn.itsource.pethome.constants.BaseConstants;
import cn.itsource.pethome.system.login.domain.PhoneRegister;
import cn.itsource.pethome.system.login.domain.WechatBinder;
import cn.itsource.pethome.system.login.domain.WechatCode;
import cn.itsource.pethome.system.logininfo.domain.LoginRO;
import cn.itsource.pethome.system.logininfo.service.ILogininfoService;
import cn.itsource.pethome.system.user.domain.User;
import cn.itsource.pethome.system.user.service.IUserService;
import cn.itsource.pethome.system.wxuser.domain.Wxuser;
import cn.itsource.pethome.system.wxuser.service.IWxuserService;
import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.BusinessException;
import cn.itsource.pethome.utils.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
//这里是说明你这个类是干什么用的
@Api(value = "登录API",description="登录的功能")
public class LoginController {
    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private IWxuserService wxuserService;
    @Autowired
    private ILogininfoService logininfoService;
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 1.获取到授权码
     * 2.拼接获取令牌的地址
     * 3.发送请求-接收返回的数据(获取到令牌)
     *   3.1 根据获取到的unionid 去查询数据看  看有没有数据
     *       如果没有 3.1.1就发送请求去获取用户信息  最终将数据保存到数据库里面 跳转绑定页面 (后面还要去绑定账号)
     *       如果有  3.1.2 并且user_id 有值  直接登录成功  如果user_id为null 跳转绑定页面
     *
     * @return
     */
    @ApiOperation(value = "微信登录的接口" )
    @PostMapping("/wechat")
    public AjaxResult wechat(@RequestBody WechatCode wechatCode) {
        //获取令牌
        String code = wechatCode.getCode();
        if (code == null){
            throw new BusinessException("非法访问！");
        }
        String url = wxConfig.getAccessTokenUrl(code);
        //发送get请求  得到一个字符串
        String result = HttpClientUtils.httpGet(url);
        //将json字符转为json对象 当成map使用
        JSONObject jsonObject = JSONObject.parseObject(result);
        String access_token = jsonObject.getString("access_token");
        String unionid = jsonObject.getString("unionid");
        String openid = jsonObject.getString("openid");
        if ("".equals(access_token)||access_token == null){
            throw new BusinessException("非法访问！");
        }
        Wxuser byUnionid = wxuserService.findByUnionid(unionid);
        if (byUnionid == null){//byUnionid == null 就说明用户是第一次
            String userinfoUrl = wxConfig.getUserinfoUrl(access_token, openid);
            //得到用户的所有信息
            String user = HttpClientUtils.httpGet(userinfoUrl);
            Wxuser wxuserResult = JSONObject.parseObject(user, Wxuser.class);
            //保存用户信息到wxuser表
            wxuserService.add(wxuserResult);
            //跳转绑定页面
            return AjaxResult.success().setMsg("NoBind").setData(unionid);
        }else {
            //如果为空说明没有和user表进行绑定
            if (byUnionid.getUserId() == null){
                //跳转绑定页面
                return AjaxResult.success().setMsg("NoBind").setData(unionid);
            }else {
                Long userId = byUnionid.getUserId();
                User user = userService.findnoe(userId);
                LoginRO loginRO = new LoginRO();
                loginRO.setPassword(user.getPassword());
                loginRO.setUsername(user.getUsername());
                loginRO.setType(BaseConstants.Logininfo.STATE_USER);
                loginRO.setAutoLogin(false);
                return logininfoService.account(loginRO);
            }
        }
    }
    @ApiOperation(value = "微信绑定的接口" )
    @PostMapping("/wechat/binder")
    public AjaxResult wechatBinder(@RequestBody WechatBinder wechatBinder) {
        //校验手机 、 验证码 、unionid
        if (wechatBinder.getPhone() == null) {
            throw new BusinessException("手机号不能为空!");
        }
        if (wechatBinder.getVerifyCode() == null) {
            throw new BusinessException("验证码不能为空!");
        }
        if (wechatBinder.getUnionid() == null) {
            throw new BusinessException("非法访问!");
        }
        //前端用户输入的验证码
        String verifyCode = wechatBinder.getVerifyCode();
        //存入ridias的验证码取出来
        Object obj = redisTemplate.opsForValue().get(wechatBinder.getPhone() + BaseConstants.Vcode.BIND);
        if(obj == null){
            throw new BusinessException("验证码已过期!");
        }
        if(!obj.equals(verifyCode)){
            throw new BusinessException("验证码输入错误!");
        }
        //验证手机号是否已经被注册
        User byPhone = userService.findByPhone(wechatBinder.getPhone());
        if (byPhone != null){
            Wxuser byUserId = wxuserService.findByUserId(byPhone.getId());
            if (byUserId!=null){//说明已经绑定了
                throw new BusinessException("该手机号已经被绑定了!");
            }else {//没有绑定 就调用方法
                executeBind(wechatBinder,byPhone);
            }
        }else {
            PhoneRegister phoneRegister = new PhoneRegister();
            phoneRegister.setPhone(wechatBinder.getPhone());
            phoneRegister.setPassword("111111");
            Long userid = userService.add(phoneRegister);
            byPhone = new User();
            //给当前手机号发送短信 告诉他密码  提示他去修改密码
            byPhone.setId(userid);
            executeBind(wechatBinder, byPhone);

            byPhone.setUsername(wechatBinder.getPhone());
            byPhone.setPassword(phoneRegister.getPassword());
        }
        LoginRO loginRO = new LoginRO();
        loginRO.setPassword(byPhone.getPassword());
        loginRO.setUsername(byPhone.getUsername());
        loginRO.setType(BaseConstants.Logininfo.STATE_USER);
        loginRO.setAutoLogin(false);
        return logininfoService.account(loginRO);

    }
    private void executeBind(WechatBinder wechatBinder, User byPhone) {//修改保存wxuser表的UserId
        Wxuser byUnionid = wxuserService.findByUnionid(wechatBinder.getUnionid());
        if (byUnionid == null) {
            throw new BusinessException("非法访问!");
        }
        byUnionid.setUserId(byPhone.getId());
        wxuserService.update(byUnionid);
    }
}
